package cn.chinaiptv.serverlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.chinaiptv.bean.User;
import cn.chinaiptv.user.UserReaderWriter;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public LoginServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String code = request.getParameter("code");
		String sessionCode = (String) request.getSession().getAttribute("code");
		UserReaderWriter urw = new UserReaderWriter();
		String realPassword = urw.readUserPassword("user1");

		if (!sessionCode.equals(code)) {
			request.setAttribute("errorInfo", "验证码错误");
			RequestDispatcher ds = request.getRequestDispatcher("/login.jsp");
			ds.forward(request, response);
			return;
		}

		if ("adminstrator".equals(username)
				&& "adminstratorPWD".equals(password)) {
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			request.getSession().setAttribute("user", user);

			response.sendRedirect(request.getContextPath() + "/update.jsp");
		} else if (realPassword != null) {

			if (realPassword.equals(password)) {
				User user = new User();
				user.setPassword(realPassword);
				user.setUsername("user1");
				request.getSession().setAttribute("user", user);
				response.sendRedirect(request.getContextPath() + "/update.jsp");
			} else {
				out.write("错误的用户名或密码.2秒后转向登录页面");
				response.setHeader("Refresh",
						"2;URL=" + request.getContextPath() + "/login.jsp");
				return;
			}
		} else {
			out.write("错误的用户名或密码.2秒后转向登录页面");
			response.setHeader("Refresh", "2;URL=" + request.getContextPath()
					+ "/login.jsp");
			return;
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doGet(request, response);
	}

}
